package com.mocha.nezha.nezha;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Scheduler;
import com.mocha.nezha.dmo.VehicleBO;
import com.mocha.nezha.dmo.VehicleTrackDTO;
import com.scshyzh.concurrent.MochaThreadFactory;
import lombok.Getter;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


/**
 * @author: songkui
 * @since 2022-01-19
 */
public class VehicleCache {


    private final static long EXPIRE_TIME  = 600L;
    //key: vehicleNo;
    @Getter
    private final Cache<String, VehicleBO> cache;
    @Getter
    private String parkCode;

    public VehicleCache(String parkCode){
        cache = Caffeine.newBuilder()
                .removalListener(new VehicleExpireHandler())
                .expireAfterAccess(EXPIRE_TIME,  TimeUnit.SECONDS)
                .scheduler(Scheduler.forScheduledExecutorService(Executors.newScheduledThreadPool(1, new MochaThreadFactory("vehicle-cache"))))
                .build();

        this.parkCode = parkCode;
    }



    public VehicleBO getVehicle(String parkCode, VehicleTrackDTO trackDTO){
        VehicleBO vehicleBO = cache.getIfPresent(trackDTO.getVno());
        if (null != vehicleBO){
//            if (null == vehicleBO.getVehicleNo() && StrUtil.isNotEmpty(trackDTO.getVno())){
//                vehicleBO.setVehicleNo(trackDTO.getVno());
//            }
            return vehicleBO;
        }

        vehicleBO = new VehicleBO(parkCode, trackDTO.getOid(), trackDTO.getVno());
        cache.put(vehicleBO.getVehicleNo(), vehicleBO);

        return vehicleBO;
    }



}
